package com.ease.integration.log;

import java.util.Iterator;
import java.util.Map;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * RMI的日志拦截器 负责记录应用服务器和接口服务器间传送的DTO信息
 * 
 * @author nathanleewei
 * 
 */
public class RmiServiceLogger implements MethodInterceptor {

	private static final Log logger = LogFactory.getLog(RmiServiceLogger.class);

	public Object invoke(MethodInvocation invocation) throws Throwable {
		String methodName = invocation.getMethod().getName();
		Object[] argv = invocation.getArguments();
		if (null != argv) {
			StringBuffer argsbuf = new StringBuffer();
			for (int i = 0; i < argv.length; i++) {
				Object arg = invocation.getArguments()[i];
				argsbuf.append("arg[" + i + "]'s class: " + arg.getClass() + "\r\n");
				Map properties = BeanUtils.describe(arg);
				for (Iterator it = properties.keySet().iterator(); it.hasNext();) {
					Object key = it.next();
					Object value = properties.get(key);
					argsbuf.append("\tkey: " + key + "\t" + "value: " + value + "\r\n");
				}
			}
			if (logger.isDebugEnabled()) {
				logger.debug(methodName + " RMI invoke\r\n" + argsbuf.toString() + "\r\n\r\n");
			}
		}
		Object obj = null;
		try {
			obj = invocation.proceed();
		} catch (Exception e) {
			logger.error("RMI invoke failed.", e);
		}
		if (logger.isDebugEnabled()) {
			if (null != obj) {
				StringBuffer argsbuf = new StringBuffer();
				argsbuf.append("response's class: " + obj.getClass() + "\r\n");
				Map properties = BeanUtils.describe(obj);
				for (Iterator it = properties.keySet().iterator(); it.hasNext();) {
					Object key = it.next();
					Object value = properties.get(key);
					argsbuf.append("\tkey: " + key + "\t" + "value: " + value + "\r\n");
				}
				logger.debug(methodName + " RMI return\r\n" + argsbuf.toString() + "\r\n\r\n");
			} else {
				logger.debug(methodName + " RMI return null\r\n\r\n");
			}
		}
		return obj;
	}

}
